package com.example.demo_homework2.service;

import com.example.demo_homework2.bean.CmsArticle;
import com.example.demo_homework2.bean.CmsCategory;
import com.example.demo_homework2.common.Response;
import com.example.demo_homework2.mapper.CmsArticleMapper;
import com.example.demo_homework2.mapper.CmsCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CmsArtcleService {
    @Autowired
    private CmsArticleMapper articleMapper;
    @Autowired
    CmsCategoryMapper categoryMapper;

    public boolean saveOrUpdate(String id, String title, String author, String categoryId) {
        if (categoryId != null && !"".equals(categoryId)) {
            CmsCategory c = categoryMapper.selectByPrimaryKey(categoryId);
            if (c == null) {
                return false;
            }
        }
        if (id == null || "".equals(id)) {
            CmsArticle cmsArticle = new CmsArticle();
            cmsArticle.setId(UUID.randomUUID().toString());
            cmsArticle.setTitle(title);
            cmsArticle.setCategoryId(categoryId);
            cmsArticle.setMemberName(author);
            cmsArticle.setStatus("待审核");
            cmsArticle.setReadNum(0);
            CmsCategory c=categoryMapper.selectByPrimaryKey(categoryId);
            String s=c.getName();
            System.out.println("s="+s);
            cmsArticle.setCategoryName(s);
            articleMapper.insert(cmsArticle);
        } else {
            CmsArticle article = articleMapper.selectByPrimaryKey(id);
            if (article == null) {
                return false;
            } else {
                article.setCategoryId(categoryId);
                article.setTitle(title);
                article.setMemberName(author);
                CmsCategory c=categoryMapper.selectByPrimaryKey(categoryId);
                article.setCategoryName(c.getName());
                articleMapper.updateByPrimaryKey(article);
            }
        }
        return true;
    }

    public int deleteArticle(String id) {
        return articleMapper.deleteByPrimaryKey(id);
    }

    public int deleteArticleByIds(String[] ids) {
        return articleMapper.deleteArticleByIds(ids);
    }

    public CmsArticle getArticleById(String id) {
        CmsArticle cmsArticle = articleMapper.selectByPrimaryKey(id);
        return cmsArticle;
    }
    public List<CmsArticle> searchBy(Date begin, Date end,String key){
        return articleMapper.selectBy(begin,end,key);
    }

    public boolean updateState(String artId,String state){
       int i =articleMapper.updateStateById(artId ,state);
        if (i==0) {
            return false;
        }
        else{
            return true;
        }
    }
}
